/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.orderView.dish;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TCommodity;
import com.ruipengkj.bean.TProductCatalog;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.component.RPJButtonDish;
import com.ruipengkj.component.page.PageDelegale;
import com.ruipengkj.component.page.PagingComponent;
import com.ruipengkj.service.TCommodityService;
import com.ruipengkj.service.TProductCatalogService;
import com.ruipengkj.view.base.BasePanel;
/**
 * 说明：
 * 菜品面板
 */
public class OrderDishPanel extends BasePanel implements ComponentListener, PageDelegale {

	private static final long serialVersionUID = 1L;
	
	private JPanel dishNamePanel;//菜品（名称）面板
	
	private PagingComponent pagingComponent;//翻页组建
	
	private TProductCatalog tProductCatalog;//商品分类
	private TProductCatalogService tProductCatalogService = BuildSpringApplication.getInstance().getTProductCatalogServiceImpl();//商品分类
	
	private TCommodityService tCommodityService = BuildSpringApplication.getInstance().getTCommodityServiceImpl();
	private String CatalogId = null;
	
	private int num = 1;//每頁的數量
	private int currentPage = 0;//从第几条数据查起
	private int count = 0;//总数
	
	public OrderDishPanel() {
		init();
		this.addComponentListener(this);
	}
	
	private void init() {
		dishNamePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		dishNamePanel.setOpaque(false);
		
		pagingComponent = new PagingComponent();
		pagingComponent.setPageDelegale(this);
		pagingComponent.setOpaque(false);
		pagingComponent.setLayout(new FlowLayout(FlowLayout.CENTER));
		
		this.setLayout(new BorderLayout());
		this.add(dishNamePanel, BorderLayout.CENTER);
		this.add(pagingComponent, BorderLayout.SOUTH);
	}
	
	private void initFlowPanel() {
//		dishNamePanel.removeAll();
//		for (int i = 0; i < num; ++i) {
//			dishNamePanel.add(new RPJButtonDish("", this));
//		}
		int count = dishNamePanel.getComponentCount();
		if (count > num) {
			for (int i = count - 1; i >= num; --i) {
				dishNamePanel.remove(i);
			}
		} else {
			for (int i = count; i < num; ++i) {
				dishNamePanel.add(new RPJButtonDish(" ", this));
			}
		}
		termQuery();
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		for (int i = dishNamePanel.getComponentCount() - 1; i >= 0; --i) {
			if (e.getSource() == dishNamePanel.getComponent(i)) {
				AddDish(((RPJButtonDish)e.getSource()).gettCommodity());
			}
		}
	}
	
	public void byTypeQueryDish(String CatalogId) {
		this.CatalogId = CatalogId;
		termQuery();
	}
	
	//查询条件：分类，list储存条件
	private void queryCatalogTerm(List<TProductCatalog> tProductCatalogList, TProductCatalog parent) {
		if (tProductCatalog == null || tProductCatalog.getCatalogID() == null || tProductCatalog.getCatalogID().equals("")) {
			return;
		}
		List<TProductCatalog> list = null;
		try {
			TProductCatalog tProductCatalog = new TProductCatalog();
			tProductCatalog.setTProductCatalog(parent);
			list = tProductCatalogService.findService(tProductCatalog);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (list != null && list.size() != 0) {
			for (int i = list.size() - 1; i >= 0; --i) {
				tProductCatalogList.add(list.get(i));
				queryCatalogTerm(tProductCatalogList, list.get(i));
			}
		}
		return;
	}
		
	//查询总条数
	private void countQuery(String sql) {
		sql = sql.replace(" o.commodityID, o.price, o.name, o.discountPrice, o.barcode, o.batchPrice, o.unit, o.avgPrice, o.disCount", " count(*) ");
		sql = sql.replace(" limit "+ currentPage + "," + num, "");
		
		List<Object[]> objectList = tCommodityService.querySQL(sql);
		if (objectList != null && objectList.size() > 1) {
			this.count = Integer.parseInt(objectList.get(1)[0].toString());
		}
	}
		
	//組裝sql語句
	private String createSql(List<TProductCatalog> tProductCatalogList) {
		String sql = ApplicationContext.commodity_sql_sales;
		
		if (tProductCatalogList != null && tProductCatalogList.size() != 0) {
			sql += " and (";
			for (int i = tProductCatalogList.size() - 1; i >= 0; --i) {
				TProductCatalog tProductCatalog = tProductCatalogList.get(i);
				if(tProductCatalog!=null&&tProductCatalog.getCatalogID()!=null&&!tProductCatalog.getCatalogID().equals("")){
					sql += "p.catalogid='"+tProductCatalog.getCatalogID()+"' or ";
				}
			}
			if(sql.length()>4) {
				sql = sql.substring(0, sql.length()-4);
				sql += ")";
			}
		}
		
		sql += " order by p.Priority ASC limit "+ currentPage + "," + num;
		
		return sql;
	}
	//条件查询
	protected void termQuery(){
		new Thread() {
			@Override
			public void run() {
				try {
					if (dishNamePanel.getComponentCount() <= 0) {
						return;
					}
					List<TProductCatalog> tProductCatalogList = null;
					if(null!=CatalogId && !CatalogId.equals("")){
						tProductCatalog=new TProductCatalog(CatalogId);
						
						//递归查出所有子类
						tProductCatalogList = new ArrayList<TProductCatalog>();
						queryCatalogTerm(tProductCatalogList, tProductCatalog);
						
						tProductCatalogList.add(tProductCatalog);
					}
					String sql = createSql(tProductCatalogList);
					
					System.out.println(sql);
					countQuery(sql);
					List<Object[]> objectList =tCommodityService.querySQL(sql);
					
					//清空菜品
					for (int i = dishNamePanel.getComponentCount() - 1; i >= 0; --i) {
						RPJButtonDish db = (RPJButtonDish)dishNamePanel.getComponent(i);
						db.setEnabled(false);
						db.settCommodity(null);
						db.setText("");
					}
					//添加菜品
					if(objectList!=null){
						for (int i = objectList.size() - 1; i > 0; --i) {
							Object[] objects = objectList.get(i);
							
							TCommodity tCommodity = new TCommodity(
									(String)objects[0],//commodityID
									(Double)objects[1],//price
									(String)objects[2],//name
									(Double)objects[3],//discountPrice
									(String)objects[4],//barcode
									(Double)objects[5],//batchPrice
									(String)objects[6],//unit
									(Double)objects[7],//avgPrice
									(Double)objects[8]//disCount
							);
							
							RPJButtonDish db = (RPJButtonDish)dishNamePanel.getComponent(i-1);
							db.setEnabled(true);
							db.settCommodity(tCommodity);
							db.repaint();
						}
						pagingComponent.show();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	@Override
	public String getInfo() {
		int j = count%num == 0 ? count/num : count/num+1;
		
		if (j == 1 && currentPage != 0) {
			homePage();
		}
		
		return "当前第 " + (currentPage/num+1) + " 页/共 "+ j + " 页";
	}
	//首页
	@Override
	public void homePage() {
		currentPage = 0;
		termQuery();
	}
	
	@Override
	public void lastPage() {
		if (count >= num) {
			currentPage = count - count%num;
		}
		termQuery();
	}

	@Override
	public void nextPage() {
		if (currentPage < count - num) {
			currentPage += num;
		}
		termQuery();
	}

	@Override
	public void prevPage() {
		if (currentPage >=num)
			currentPage -= num;
		else
			currentPage = 0;
		termQuery();
	}
	
	public void AddDish(TCommodity tCommodity) {}

	@Override
	public void clear() {
		
	}

	//610 5 --> 122
	//30+65*x
	@Override
	public void componentHidden(ComponentEvent arg0) {
//		System.out.println("组件变得不可见时调用。");
	}

	@Override
	public void componentMoved(ComponentEvent c) {
//		System.out.println("组件位置更改时调用。");
//		System.out.println(c.getComponent().getHeight()+ "   " +c.getComponent().getWidth());
//		initFlowPanel();
	}

	@Override
	public void componentResized(ComponentEvent c) {
//		System.out.println("组件大小更改时调用。");
//		System.out.println(c.getComponent().getHeight()+ "   " +c.getComponent().getWidth());
		num = (c.getComponent().getHeight()-30)/65 * (c.getComponent().getWidth()/122);
		if ((num > dishNamePanel.getComponentCount() || num < dishNamePanel.getComponentCount()) && num != 0) {
			initFlowPanel();
			this.updateUI();
		}
	}

	@Override
	public void componentShown(ComponentEvent arg0) {
//		System.out.println("组件变得可见时调用。");
	}

}
